package com.app.micaihu.service;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.receiver.NoticeReceiver;
import com.app.utils.NetUtils;
import com.app.micaihu.utils.NotifyUtil;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.file.AppFileUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 下载服务,下载完成即可关闭
 *
 * @author linkai
 */
public class DownLoadService extends Service {

    private int requestCode = (int) SystemClock.uptimeMillis();
    private static int oldNotifyId = 1100;//第一个通知栏的下载通知id默认为1100

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) return super.onStartCommand(intent, flags, startId);
        //获取下载参数
        String download_url = intent.getStringExtra("download_url");
        String savePath = intent.getStringExtra("download_path");
        String title = intent.getStringExtra("download_title");
        String content = intent.getStringExtra("download_content");
        String ticker = intent.getStringExtra("download_ticker");
        //设置想要展示的数据内容
        int currentNotifyId = oldNotifyId++;
        final Intent intent_noti = new Intent(getApplicationContext(), NoticeReceiver.class); //点击通知之后要发送的广播
        intent_noti.setAction(NoticeReceiver.DOWNLOAD_PUSH_ACTION);
        intent_noti.putExtra("notifyId", currentNotifyId + "");
        intent_noti.putExtra("download_path", savePath);
        PendingIntent pendIntent = PendingIntent.getBroadcast(this,
                requestCode, intent_noti, PendingIntent.FLAG_UPDATE_CURRENT);
        //实例化工具类，并且调用接口
        NotifyUtil notify7 = new NotifyUtil(this, currentNotifyId);

        notify7.notify_progress(pendIntent, getApplicationContext(), R.mipmap.icon, ticker, title, content,
                false, false, false, download_url, savePath, new NotifyUtil.DownLoadListener() {
                    @Override
                    public void OnSuccess(File file) {
                        //关闭下载服务
                        DownLoadService.this.stopSelf();
                        //跳转安装文件
                        AppFileUtils.installFile(file, getApplicationContext());
                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        DownLoadService.this.stopSelf();
                    }
                });
//        RemoteViews rv = new RemoteViews(getPackageName(),R.layout.notification_down);
//        notify7.notify_dwon(rv,pendIntent,R.mipmap.icon,ticker,title,false,false,false,download_url, savePath, new NotifyUtil.DownLoadListener() {
//                    @Override
//                    public void OnSuccess(File file) {
//                        //关闭下载服务
//                        DownLoadService.this.stopSelf();
//                        //跳转安装文件
//                        AppFileUtils.installFile(file, getApplicationContext());
//                    }
//
//                    @Override
//                    public void onFailure(Throwable t, int errorNo, String strMsg) {
//                        DownLoadService.this.stopSelf();
//                    }
//                });
        return super.onStartCommand(intent, flags, startId);

    }


    /**
     * 开始下载apk文件
     */
    public static void startDownLoadApk(final Context context, final String url, final String title) {
        int netType = NetUtils.getNetworkType();
        if (netType == NetUtils.NETTYPE_WIFI) {
            startDownService(context, url, title);
        } else if (netType == NetUtils.NETTYPE_CM) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(AppApplication.getInstance().getString(R.string.down_tips));
            builder.setPositiveButton(context.getString(R.string.down_goindown), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    startDownService(context, url, title);
                }
            });
            builder.setNegativeButton(context.getString(R.string.down_cancle), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            try {
                if (!((Activity) context).isFinishing()) {
                    builder.create().show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ToastUtils.makeText(AppApplication.getInstance().getString(R.string.adjutant_error));
        }

    }


    /**
     * 开启下载服务
     *
     * @param context
     * @param url
     */
    private static void startDownService(Context context, String url, String fileTitle) {

        if (TextUtils.isEmpty(url)) {
            ToastUtils.makeText("下载失败,下载链接为空");
            return;
        }

        url = url.trim();

        if (NotifyUtil.checkUrlLoading(url)) {
            ToastUtils.makeText("正在下载中...");
            return;
        }
        if (context == null) {
            ToastUtils.makeText("下载异常,请重新下载");
            return;
        }
        ToastUtils.makeText("开始下载");
        Intent intent = new Intent(context, DownLoadService.class);
        String target;
        try {
            target = AppConfigTools.APKFLODER + AppConfigTools.SPREARATOR + url.substring(url.lastIndexOf("/") + 1);
        } catch (Exception e) {
            target = AppConfigTools.APKFLODER + AppConfigTools.SPREARATOR + "download.apk";
            e.printStackTrace();
        }
        String title;
        try {
            if (TextUtils.isEmpty(fileTitle)) {
                title = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
            } else {
                title = fileTitle;
            }
            title = URLDecoder.decode(title, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            title = "文件下载";
        } catch (Exception e) {
            title = "文件下载";
        }
        intent.putExtra("download_url", url);
        intent.putExtra("download_title", title);
        intent.putExtra("download_content", "正在下载中");
        intent.putExtra("download_ticker", "正在下载中");
        intent.putExtra("download_path", target);
        if (context != null) {
            context.startService(intent);
        }
    }

}
